﻿/*
 * Copyright (c) 2015-2016 Constantijn Evenhuis (blueprints@const.nl)
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
using Blueprints.IO;
using System;
using System.IO;

namespace Blueprints.Editing
{
    partial class EditContext
    {
        private int? savedVersion = null;

        /// <summary>
        /// Gets whether there are unsaved changes in this EditContext.
        /// </summary>
        public bool HasUnsavedChanges
        {
            get
            {
                return savedVersion != Version;
            }
        }

        /// <summary>
        /// Creates a new blueprint to edit.
        /// </summary>
        /// <param name="rootType">The type of the root object.</param>
        public void New(string rootType = null)
        {
            MediaType = MediaType.Unknown;
            NodeCollection nodes = new NodeCollection();
            nodes.Add(new EditNode(this, new StartNode(StartNode.GetValidNodeName(rootType, "Blueprint"), rootType, null, null)));
            nodes.Add(new EditNode(this, new EndNode()));
            undo.Clear();
            redo.Clear();
            Nodes = nodes;
            RootNode = GetRootNode(nodes);
            DocumentUri = new Uri("document:" + Guid.NewGuid().ToString());
            savedVersion = Synchronize(RootNode);
        }

        /// <summary>
        /// Loads a blueprint to edit.
        /// </summary>
        /// <param name="stream">The stream from which to load the blueprint.</param>
        /// <param name="uri">The uri at which the blueprint is located.</param>
        /// <param name="mediaType">The media type of the stream.</param>
        public void Load(Stream stream, Uri uri = null, MediaType mediaType = MediaType.Unknown)
        {
            if (uri == null)
            {
                uri = new Uri("document:" + Guid.NewGuid().ToString());
            }
            else if (mediaType == MediaType.Unknown)
            {
                mediaType = uri.GetMediaType();
            }

            if (mediaType == MediaType.Unknown)
            {
                mediaType = MediaType.Xml;
            }

            DocumentUri = uri;
            MediaType = mediaType;
            NodeCollection nodes = new NodeCollection();
            using (IBlueprintReader reader = BlueprintResolver.CreateReader(stream, uri, mediaType))
            {
                while (reader.MoveNext())
                {
                    nodes.Add(new EditNode(this, reader.Current));
                }
            }

            undo.Clear();
            redo.Clear();
            Nodes = nodes;
            RootNode = GetRootNode(nodes);
            savedVersion = Synchronize(RootNode);
        }

        /// <summary>
        /// Loads a blueprint to edit.
        /// </summary>
        /// <param name="instance">The object instance to edit.</param>
        public void Load(object instance)
        {
            DocumentUri = new Uri("document:" + Guid.NewGuid().ToString());
            MediaType = MediaType.Xml;

            NodeCollection nodes = new NodeCollection();
            using (BlueprintContext context = new BlueprintContext(instance.GetType()))
            using (EditNodeWriter writer = new EditNodeWriter(this))
            {
                context.Serialize(writer, instance);
                nodes = new NodeCollection(writer.Nodes);
            }

            undo.Clear();
            redo.Clear();
            Nodes = nodes;
            RootNode = GetRootNode(nodes);
            savedVersion = Synchronize(RootNode);
        }

        /// <summary>
        /// Saves the blueprint.
        /// </summary>
        /// <param name="stream">The stream to which to save the blueprint.</param>
        /// <param name="uri">The uri at which the blueprint is saved.</param>
        /// <param name="mediaType">The media type to save the blueprint as.</param>
        public void Save(Stream stream, Uri uri = null, MediaType mediaType = MediaType.Unknown)
        {
            if (uri == null)
            {
                uri = DocumentUri;
            }

            if (mediaType == MediaType.Unknown)
            {
                mediaType = uri.GetMediaType();
            }

            if (mediaType == MediaType.Unknown)
            {
                mediaType = MediaType;
            }

            using (IBlueprintWriter writer = BlueprintResolver.CreateWriter(stream, uri, mediaType))
            {
                foreach (EditNode node in Nodes)
                {
                    writer.Write(node.TraceableNode);
                }
            }

            savedVersion = Version;
        }
    }
}
